//----------环境模式设置-----生产模式:production--开发模式:development--------

require('marko/node-require'); //加入marko 模板的支持
let compression = require('compression');
let express = require("express");
let fs = require("fs");
let path = require("path");
let favicon = require("serve-favicon");
let logger = require("morgan");

let cookieParser = require("cookie-parser");
let bodyParser = require("body-parser");
let history = require("connect-history-api-fallback");
let app = express();



app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
app.set("RootPath", __dirname);


let rewrites = [{
        from: /^\/dist\/.*$/,
        to: function (context) {
            return context.parsedUrl.pathname;
        }
    },
    {
        from: /^\/static\/.*$/,
        to: function (context) {
            return context.parsedUrl.pathname;
        }
    },
    {
        from: /^\/res\/.*$/,
        to: function (context) {
            return context.parsedUrl.pathname;
        }
    }
];
let homeAddr = "vue";
//后端路由 从哪里来到哪里去
let areasDir = fs.readdirSync(path.resolve(__dirname, "areas"));
areasDir.map(function (dir) {
    if (!dir.startsWith(".")) {
        let router = require(`./areas/${dir}/router`).init();
        let nameSpace = router.nameSpace.replace('/', '');
        let fr;
        if (nameSpace.length === 0) {
            homeAddr = 'node';
            //fr = eval("/^\\/.*$/i");
        } else {
            fr = eval("/^\\/" + nameSpace + "\\/.*$/i");
            rewrites.push({
                from: fr,
                to: function (context) {
                    return context.parsedUrl.pathname;
                }
            });
        }


    }
});
//前端路由 转向到 dist 下
let distDir = fs.readdirSync(path.resolve(__dirname, "www/dist"));
distDir.map(function (dir) {
    if (!dir.startsWith(".")) {
        let fr = eval("/^\\/" + dir + "\\/.*$/i");
        rewrites.push({
            from: fr,
            to: "/dist/" + dir + "/index.html"
        });
    }
});
if (homeAddr === 'vue') {
    rewrites.push({
        from: /^\/.*$/i,
        to: "/dist/home/index.html"
    });
} else {
    rewrites.push({
        from: /^\/.*$/i,
        to: function (context) {
            return context.parsedUrl.pathname;
        }
    });
}


let Rewrites = {
    //index: "/index.html",
    rewrites: rewrites
};
app.use(compression());//启用gzip
app.use(history(Rewrites)); //将vue运用为histroy模式
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger("dev"));
app.use(bodyParser.json({
    limit: '50mb'
}));
app.use(bodyParser.urlencoded({
    limit: '50mb',
    extended: true
}));
app.use(cookieParser());

app.use("/dist", express.static(path.join(__dirname, "www/dist")));
app.use("/static", express.static(path.join(__dirname, "www/static")));
app.use("/res", express.static(path.join(__dirname, "www/res")));


let router = require("./router");
router.GetRouter(app);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    let err = new Error("Not Found");
    err.status = 404;
    next(err);
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = global.NODE_ENV === "development" ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render("error");
});

//let Server = require("./server");
//Server.Start();//启动调度任务
module.exports = app;
